<template>
  <view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>

    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoGoodsDetail(item.goods_id)">
        <view class="goods-item">{{item.goods_name}}</view>
        <uni-icons type="arrowrigth" size="17"></uni-icons>
      </view>
    </view>

    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="cleanHistoryItem()"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <!-- 这里不应该点击历史记录就去哪，而是点击历史记录去搜索，反而更好，更适合真实的应用场景 -->
        <uni-tag :text="item" v-for="(item, i) in searchHistorys" :key="i" @click="gotoGoodsDetail(item.goods_id)">
        </uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null, // 用于开启定时器，作为搜索关键词自动显示的时间
        keyWord: "", // 关键词
        searchResults: [], // 搜索结果
        searchHistory: [], // 搜索历史
      };
    },
    onLoad() {
      // 重载页面时，把搜索记录再调出来
       this.searchHistory = JSON.parse(uni.getStorageSync('keyWord') || '[]');
    },
    methods: {
      // 获取输入框的关键字来进行检索
      input(e) {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.keyWord = e;
          this.getSearchResults();
        }, 500)
      },
      // 申请搜索结果
      async getSearchResults() {
        if (this.keyWord == "") {
          this.searchResults = [];
          return;
        }
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.keyWord
        });
        if (res.meta.status !== 200) return uni.$showMsg();
        this.searchResults = res.message;
        this.saveSearchKeyWords();
      },
      // 根据搜索结果跳转到对应的商品页面
      gotoGoodsDetail(goods_id) {
        uni.navigateTo({
          url: "/subpkg/goods_detail/goods_detail?goods_id=" + goods_id
        })
      },
      // 把搜索结果存起来
      saveSearchKeyWords() {
        // 转成set对象来处理关键词重复
        const set = new Set(this.searchHistory);
        set.delete(this.keyWord);
        set.add(this.keyWord);
        // 最后将set对象再转回来变成数组
        this.searchHistory = Array.from(set);
        console.log(this.searchHistory);
        // 将搜索历史永久存储到本地
        uni.setStorageSync('keyWord', JSON.stringify(this.searchHistory))
        // 记得去onLoad里面每次都加载出来
      },
      // 清空搜索记录
      cleanHistoryItem() {
        this.searchHistory = [];
        uni.setStorageSync("keyWord", '[]');
      }
    },
    computed: {
      // 将搜索历史的顺序调成按时间搜索的
      searchHistorys() {
        return [...this.searchHistory].reverse();
      }
    }
  }
</script>

<style lang="scss">
  // 让搜索框吸顶
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>
